# -*- coding: utf-8 -*-
from cache.topic_gallery_cache import refresh_topic_gallery_cache

import base64
import hashlib

try:
    import ujson as json
except:
    import json
import tornado
import tornado.web
from controls import mongo
from controls import data_topic_title_mysql
from controls import data_topic_gallery_mysql
from controls import data_topic_note_mysql
from controls import data_topic_note_img_mysql
from controls import data_manage_user_mysql
from controls import data_user_feed_mysql
from utils.file_util import file_upload
from utils import log
from config import etc

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("username")

class ManageTopicHandler(BaseHandler):
    def get(self, ):
        if not self.current_user:
            self.redirect("/cms/signin")
            return
        self.render('cms/manage_topic.html')
        return

    def post(self,):
        provid = self.get_argument('provid')
        title = self.get_argument('title')
        summary = self.get_argument('summary')

        if not (provid and title and summary):
            res = {'ret': 1, 'msg': 'param error'}
            self.write(json.dumps(res))
            self.finish()
            return

        topicid = mongo.count_topicid()

        file = self.request.files['file'][0]
        file_res = file_upload(file)

        if not (file_res and file_res['ret'] == 0):
            res = {'ret': 1, 'msg': '保存图片失败'}
            self.write(json.dumps(res))
            self.finish()
            return

        new_item = {
            'topicid': topicid,
            'title': title,
            'summary': summary,
            'hot': 0,
            'cityid': 0,
            'provid': int(provid),
            'imgid': file_res['res']['imgid'],
        }

        if not data_topic_title_mysql.add_topic_title_item(new_item):
            res = {'ret': 1, 'msg': 'add error'}
            self.write(json.dumps(res))
            self.finish()
            return

        res = {'ret': 0, 'msg': '保存成功'}
        self.write(json.dumps(res))
        self.finish()
        return


class ManageTopicGalleryHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return
        return self.render('cms/topic_gallery.html')

    def post(self):
        try:
            provid = self.get_argument('provid', None)

            if provid is None:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            gallery_list = data_topic_gallery_mysql\
                .get_topic_gallery_by_provid(provid)

            res = {'ret': 0, 'msg': '成功', 'res': gallery_list}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': '失败'}
            self.write(json.dumps(res))
            self.finish()
            return


class TopicGalleryAddHandler(BaseHandler):
    def post(self):
        try:
            provid = self.get_argument('provid', None)
            gallery_info_string = self.get_argument('gallery')

            if provid is None or not gallery_info_string:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            gallery_info_list = json.loads(gallery_info_string)

            # 删除原来的
            data_topic_gallery_mysql.del_topic_gallery_item_by_provid(provid)

            # 增加新的
            for idx, gallery_info in enumerate(gallery_info_list):
                gallery_info['seq'] = idx
                gallery_info['provid'] = provid
                data_topic_gallery_mysql.add_topic_gallery_item(gallery_info)

            res = {'ret': 0, 'msg': '保存成功'}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


class TopicGalleryRefreshHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return

    def post(self):
        try:
            provid = self.get_argument('provid', None)

            if provid is None:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            refresh_topic_gallery_cache(provid)

            res = {'ret': 0, 'msg': '保存成功'}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


class TopicNoteHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return
        return self.render('cms/topic_note.html')


class TopicNoteDelHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return

    def post(self):
        try:
            noteid = self.get_argument('noteid')

            if not noteid:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            note = data_topic_note_mysql.get_topic_note_by_noteid(noteid)
            if not note:
                res = {'ret': 1, 'msg': 'get note error'}
                self.write(json.dumps(res))
                self.finish()
                return

            userid = note['userid']

            if not data_user_feed_mysql.del_user_feed({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_NOTE_POST,
                'targetid': noteid,
            }):
                res = {'ret': 1, 'msg': 'delete manage feed error'}
                self.write(json.dumps(res))
                self.finish()
                return

            if not data_topic_note_img_mysql\
                    .delete_topic_note_img_by_noteid(noteid):
                res = {'ret': 1, 'msg': 'delete img error'}
                self.write(json.dumps(res))
                self.finish()
                return

            if not data_topic_note_mysql\
                    .delete_topic_note_by_noteid(noteid):
                res = {'ret': 1, 'msg': 'delete note error'}
                self.write(json.dumps(res))
                self.finish()
                return

            res = {'ret': 0, 'msg': 'success'}
            self.write(json.dumps(res))
            self.finish()
            return

        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return

class SigninHandler(BaseHandler):
    def get(self):
        self.render('cms/manage_signin.html')
        return

    def post(self):
        try:
            username = self.get_argument('username', '')
            password = self.get_argument('password', '')

            if not (username and password):
                log.i('params fetching error')
                self.redirect("/cms/signin")
                return

            correct_password = data_manage_user_mysql.get_password_by_username(username)

            if correct_password == password.strip(' \t\n\r'):
                self.set_secure_cookie("username", self.get_argument("username"))
                self.redirect("/cms/topic")
            else:
                log.i('password not match')
                self.redirect("/cms/signin")
                return

        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return

class SignoutHandler(BaseHandler):
    def get(self):
        pass

    def post(self):
        pass

class AuthHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return
        else:
            self.redirect("/cms/topic")
            return